#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import oss2
from itertools import islice
import datetime
import hashlib
import time
import os
import sys


def print_run_time(func):
    def wrapper(*args, **kw):
        local_time = time.time()
        func(*args, **kw)
        print('[+] [%s] Run time is %.2f' %
              (func.__name__, time.time() - local_time))
    return wrapper


today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
backuptime = yesterday.strftime('%Y-%m-%d')

# 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
auth = oss2.Auth('LTAI5tRRAwxAgxLnbRQyn4JD', '0EZJo5iaxRc5mJ***')
# Endpoint以杭州为例，其它Region请按实际情况填写。
bucket = oss2.Bucket(
    auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'xidiandaily')


def display():
    # oss2.ObjectIteratorr用于遍历文件；10个
    print("目录列表:\n")
    for b in islice(oss2.ObjectIterator(bucket), 5):
        print(b.key)


# 上传文件
@print_run_time
def upload(file):
    s = bucket.put_object_from_file(file, file)
    if s.status == 200:
        print("""[+] "%s" 上传成功 """ % file)
    else:
        print("""[+] "%s" 上传失败! %d""" % (file, s.status))


# 断点续传
@print_run_time
def breakpoint_continuingly(file):
    oss2.resumable_upload(bucket, file, file)
    print("""[+] "%s" 上传成功 """ % file)


# 执行命令
@print_run_time
def cmdrun(command):
    res = os.system(command)
    return res
    # results = subprocess.run([command], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    # return results.stderr.decode('gbk') + results.stdout.decode('gbk')


@print_run_time
def FileMd5(filename):
    if not os.path.isfile(filename):
        print("""[-] "%s" 文件不存在!""" % filename)
        sys.exit(1)
    res = hashlib.md5(open(filename, 'rb').read()).hexdigest()

    print("""[+] '%s' 生成MD5: % s""" % (filename, res))
    md5file = "%s.md5" % filename
    with open(md5file, 'w') as f:
        f.write(res)


if __name__ == '__main__':
    file = 'test.txt'
    FileMd5(file)  # 生成md5文件
    upload(file)   # 上传文件
    upload('%s.md5' % file)  # 上传MD5
    # display()  # 打印目录文件
